<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="50%"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm"/>
  </BasicDrawer>
</template>
<script lang="ts" setup>
import {ref, computed, unref} from 'vue';
import {BasicForm, useForm} from '/@/components/Form/index';
import {formSchema} from './sysTenantTableData';
import {BasicDrawer, useDrawerInner} from '/@/components/Drawer';
import {sysTenantSaveApi, sysTenantUpdateApi} from "/@/api/sys/sysTenantApi";

const isUpdate = ref(true);

const id = ref(0);

const emit = defineEmits(['success'])

const [registerForm, {resetFields, setFieldsValue, validate}] = useForm({
  labelWidth: 150,
  schemas: formSchema,

  showActionButtonGroup: false,
  baseColProps: {lg: 24, md: 24},
});

const [registerDrawer, {setDrawerProps, closeDrawer}] = useDrawerInner(async (data) => {
  resetFields();
  setDrawerProps({confirmLoading: false});
  isUpdate.value = !!data?.isUpdate;
  id.value = data?.data?.id;
  if (unref(isUpdate)) {
    setFieldsValue({
      ...data.data,
    });
  }
});

const getTitle = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

async function handleSubmit() {
  try {
    const values = await validate();
    values.id = id.value;
    setDrawerProps({confirmLoading: true});

    await (!unref(isUpdate) ? sysTenantSaveApi(values) : sysTenantUpdateApi(values));
    closeDrawer();
    emit('success');
  } finally {
    setDrawerProps({confirmLoading: false});
  }
}
</script>
